package shopping.web.servlet;

import com.alipay.api.AlipayApiException;
import org.apache.commons.beanutils.BeanUtils;
import shopping.auth.Auth;
import shopping.constants.Global;
import shopping.domain.*;
import shopping.service.OrderService;
import shopping.utils.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@WebServlet(urlPatterns = "/order")
public class OrderServlet extends BaseServlet {
    private OrderService orderService = BeanFactory.newInstance(OrderService.class);

    protected void xx(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("我不需要登录");
    }
    @Auth("ROLE_USER")
    protected void yy(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("我需要登录");
    }
    @Auth("ROLE_ADMIN")
    protected void zz(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("我需要登录，并且我得是管理员");
    }


    /**
     * 支付宝回跳
     */
    protected void callback(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接受回跳请求，先验签
        Map<String, String[]> parameterMap = request.getParameterMap();
        boolean check = AlipayUtil.check(parameterMap);
        if(check){
            //验证通过，取出订单id，修改订单状态
            String oid = request.getParameter("out_trade_no");
            orderService.updateState(oid,Global.ORDER_STATE_YIFUKUAN);

            //重定向到订单页面
            response.sendRedirect("http://www.xyshopping.com:8848/qianduan/view/order/info.html?oid="+oid);
        }else{
            response.getWriter().print("？？？？");
        }
    }

    /**
     * 去付款
     */
    protected void toPay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接受收货人信息和订单号oid
        Map<String, String[]> parameterMap = request.getParameterMap();
        Order order = new Order();
        try {
            BeanUtils.populate(order,parameterMap);
        } catch (Exception e) {
        }

        //调用Service
        //更新原数据库的状态
        orderService.updateSHR(order);


        //为跳转第三方支付做准备
        try {
            String s = AlipayUtil.generateAlipayTradePagePayRequestForm(order.getOid(),"这是我的订单",0.01);

            response.getWriter().print(s);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成订单
     */
    @Auth("ROLE_USER")
    protected void generate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //前置逻辑：1. 保证处于登录状态
        User user = (User) request.getSession().getAttribute("user");
//        if(user == null){
//            noLogin();
//            return;
//        }
        //2. 购物车不能为空
        Cart cart = getCart();
        if (cart.getItems().size() == 0){
            //购物车为空
            fail("购物车没东西呀，亲");
            return;
        }

        //前置逻辑都没问题，开始保存订单信息。

        //设置订单信息
        Order order = new Order();
        //订单id --> oid
        String oid = UUIDUtil.getId();
        order.setOid(oid);
        //提交订单的时间
        order.setOrdertime(new Date());
        //总金额
        order.setTotal(cart.getTotal());
        //订单状态 0:未付款 1:已付款 2:已发货 3.已完成
        order.setState(Global.ORDER_STATE_WEIFUKUAN);
        //用户id --> uid
        order.setUid(user.getUid());

        //设置订单项 由购物项转换而来
        //先获取购物项
        Collection<CartItem> items = cart.getItems();
        ArrayList<OrderItem> orderItems = new ArrayList<>();
        for (CartItem item : items) {
            OrderItem orderItem = new OrderItem();
            orderItem.setPid(item.getProduct().getPid());
            orderItem.setOid(oid);
            orderItem.setCount(item.getCount());
            orderItem.setSubTotal(item.getSubtotal());
            orderItems.add(orderItem);
        }

        //开始存数据库
        orderService.save(order,orderItems);

        //生成订单时，返回订单号
        success(oid);
    }

    /**
     * 查询某一个订单数据
     */
    protected void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取订单id
        String oid = request.getParameter("oid");

        //调用Service查询订单方法
        //根据订单号oid进行多表查询，获得订单信息和订单项信息（商品）
        Order order = orderService.findByOidWithItems(oid);
        success(order);
    }

    /**
     * 我的订单数据
     */
    @Auth("ROLE_USER")
    protected void myOrders(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //前置逻辑：处于登录状态
        User user = (User) request.getSession().getAttribute("user");
//        if(user == null){
//            noLogin();
//            return;
//        }

        //分页查询
        //获取页面传递的页面pageNumber
        int pageNumber = GlobalUtil.mustInt(request.getParameter("pageNumber"), 1);

        //设置pageSize，一页显示多少数据
        int pageSize = 2;

        //查询 当前用户的订单信息 做分页查询
        List<Order> orders = orderService.findOrderByUid(user.getUid(), pageNumber, pageSize);

        //构建一个pageBean
        PageBean<Order> pageBean = new PageBean<>();
        pageBean.setData(orders);

        pageBean.setPageNumber(pageNumber);
        pageBean.setPageSize(pageSize);

        //根据当前用户的uid获取该用户的所有订单信息
        int total = orderService.countByUid(user.getUid());
        pageBean.setTotal(total);


        //返回
        success(pageBean);
    }

    /**
     * 获取购物车
     * @return  session中的购物车
     */
    protected Cart getCart() {
        //判断session中有没有购物车
        HttpSession session = RRHolder.getRequest().getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        if (cart == null){
            cart = new Cart();
            session.setAttribute("cart",cart);
        }
        return cart;
    }
}
